@echo off
REM 确保在发生错误时停止脚本
setlocal enabledelayedexpansion
set "ERRORLEVEL_CHECK=IF NOT !ERRORLEVEL! == 0 EXIT /B !ERRORLEVEL!"

REM 检查是否传入了必要的参数
if "%~1"=="" (
    echo ERROR: Missing INPUT_IFC argument.
    echo Usage: script.bat INPUT_IFC OUTPUT_GLB OUTPUT_JSON OUTPUT_XKT
    exit /b 1
)
if "%~2"=="" (
    echo ERROR: Missing OUTPUT_GLB argument.
    echo Usage: script.bat INPUT_IFC OUTPUT_GLB OUTPUT_JSON OUTPUT_XKT
    exit /b 1
)
if "%~3"=="" (
    echo ERROR: Missing OUTPUT_JSON argument.
    echo Usage: script.bat INPUT_IFC OUTPUT_GLB OUTPUT_JSON OUTPUT_XKT
    exit /b 1
)
if "%~4"=="" (
    echo ERROR: Missing OUTPUT_XKT argument.
    echo Usage: script.bat INPUT_IFC OUTPUT_GLB OUTPUT_JSON OUTPUT_XKT
    exit /b 1
)

REM 从命令行参数中获取文件路径
set "INPUT_IFC=%~1"
set "OUTPUT_GLB=%~2"
set "OUTPUT_JSON=%~3"
set "OUTPUT_XKT=%~4"

REM 检查并创建目标文件夹
echo Step 0: Checking and creating required directories...
for %%F in ("%OUTPUT_JSON%" "%OUTPUT_XKT%") do (
    set "TARGET_DIR=%%~dpF"
    if not exist "!TARGET_DIR!" (
        mkdir "!TARGET_DIR!"
        if !ERRORLEVEL! NEQ 0 (
            echo Failed to create directory "!TARGET_DIR!"
            exit /b 1
        )
    )
)

REM 步骤 1: 使用 xeokit-metadata 生成元数据 JSON 文件
echo Step 1: Generating metadata JSON...
.\Ifc2gltfcxconverter-4.34.1\windows\ifc2gltfcxconverter "%INPUT_IFC%" "%OUTPUT_GLB%" "%OUTPUT_JSON%"
%ERRORLEVEL_CHECK%

REM 步骤 2: 使用 xeokit-convert 将 GLTF 和元数据合并为 XKT 文件
echo Step 2: Converting GLTF and JSON to XKT...
node .\xeokit-convert\convert2xkt.js -s "%OUTPUT_GLB%" -m "%OUTPUT_JSON%" -o "%OUTPUT_XKT%" -l
%ERRORLEVEL_CHECK%